import { treeRoute } from '@/services/system/resource/menu';

let homeRouteList;
const context = require.context('', true, /^\.\/pages\/.*\.jsx$/);

const menuFormatter = menuList => {
  menuList.forEach(item => {
    try {
      if (item.icon) {
        item.icon = document.location.origin + item.icon;
      }
  
      if (item.component) {
        // eslint-disable-next-line no-param-reassign
        item.component = context(`./pages${item.component}/index.jsx`).default
      }
  
      if (item.children) {
        // eslint-disable-next-line no-param-reassign
        item.routes = menuFormatter(item.children);
      }
    } catch (e) {
      console.info(e)
    }
  })

  return menuList;
}

export function patchRoutes(routes) {
  homeRouteList.forEach(route => {
    routes.routes[0].routes[routes.routes[0].routes.length - 1].routes.unshift(route)
  })
}

export async function render(initialValue) {
  const res = await treeRoute();
  if (res.success) {
    const extraRoutes = res.data
    homeRouteList = menuFormatter(extraRoutes)

    initialValue();
  } else {
    window.location.href = '/user/login';
  }
}

